package com.time.workshop.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.pingplusplus.android.PaymentActivity;
import com.time.workshop.API;
import com.time.workshop.BaseConstant;
import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.bean.TimeHallDetail;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.Log;
import com.time.workshop.utils.NewToast;
import com.time.workshop.utils.PreferenceUtil;

public class TimeHallDetailActivity  extends SuperActivity {
	@V
	private Button timehall_titlebar_left_btn;
	@V
	private ImageView head_ImageView,bg_ImageView;
	@V
	private TextView head_name,head_statu,head_days,context,bounty_tv,
	context_detail,context_time,context_address,jiebang,pay_commit,pay_price;
	@V
	private EditText name_et,phone_et,youshi_et;
	@V
	private LinearLayout isShow_layout;
	@V
	private LinearLayout ll_pay ;
	@V
	private RelativeLayout weixin_Layout, zhifubao_Layout,pay_Layout;
	@V
	ImageView weixin_true , zhifubao_true;
	private String pay_type;

	private TimeHallDetail detail = new TimeHallDetail();
	private String ID,HEADER_IMAGE;
	private static final int REQUEST_CODE_PAYMENT = 1;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.activity_time_hall_detail);
		ID = getIntent().getStringExtra("ID");
//		HEADER_IMAGE = getIntent().getStringExtra("HEADER_IMAGE");
		init();
		getData();
	}

	private void init() {
		Injector.getInstance().inject(this);
		timehall_titlebar_left_btn.setOnClickListener(this);
		jiebang.setOnClickListener(this);
		weixin_Layout.setOnClickListener(this);
		zhifubao_Layout.setOnClickListener(this);
		pay_commit.setOnClickListener(this);
	}
	private void setData() {
		head_name.setText(detail.getUSERNAME());
		head_statu.setText(detail.getSTATUS_NAME());
		head_days.setText(detail.getC_TIME());
		context.setText(detail.getTITLE());
		if (!CommonUtils.isNull_nie(detail.getPRICE())) {
			bounty_tv.setText(detail.getPRICE()+"元");
			pay_price.setText("合计："+detail.getPRICE()+"元\n该金额先交给时间工坊做担保");
		}

		context_detail.setText(detail.getNEED_INFO());
		context_time.setText(detail.getNEED_TIME());
		context_address.setText(detail.getNEED_ADDRESS());

		if (!CommonUtils.isNull_nie(detail.getPIC_URL())) {
			ImageLoader.getInstance().displayImage(detail.getPIC_URL(), bg_ImageView, getDisplayOption());
		}
		if (!CommonUtils.isNull_nie(detail.getHEADER_IMAGE())) {
			ImageLoader.getInstance().displayImage(detail.getHEADER_IMAGE(),head_ImageView, getDisplayOption());
		}
		if (detail.isIS_SHOW() == true) 
			isShow_layout.setVisibility(View.VISIBLE);
		else 
			isShow_layout.setVisibility(View.GONE);
		if (detail.getNEED_PAY()) {
			ll_pay.setVisibility(View.VISIBLE);
			pay_Layout.setVisibility(View.VISIBLE);
		}

	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.timehall_titlebar_left_btn:
			back();
			break;
		case R.id.jiebang:
			if (CommonUtils.isNull_nie(name_et.getText().toString().trim())) {
				NewToast.makeText(TimeHallDetailActivity.this, getResources().getString(R.string.laoren_hint_name));
				break;
			}
			if (CommonUtils.isNull_nie(phone_et.getText().toString().trim())) {
				NewToast.makeText(TimeHallDetailActivity.this, getResources().getString(R.string.run_phone));
				break;
			}
			if (CommonUtils.isNull_nie(youshi_et.getText().toString().trim())) {
				NewToast.makeText(TimeHallDetailActivity.this, getResources().getString(R.string.mine_task_youshi));
				break;
			}
			taskAccept();
			break;
		case R.id.weixin_Layout:
			weixin_true.setImageResource(R.drawable.btn_choose_pressed);
			zhifubao_true.setImageResource(R.drawable.btn_choose_normal);
			pay_type = "wx";
			break;
		case R.id.zhifubao_Layout:
			zhifubao_true.setImageResource(R.drawable.btn_choose_pressed);
			weixin_true.setImageResource(R.drawable.btn_choose_normal);
			pay_type = "alipay";
			break;
		case R.id.pay_commit:
			requestPay();
			break;
		default:
			break;
		}
	}
	
	private void requestPay(){
		if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		if ("".equals(CommonUtils.isNull(pay_type))) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.toast_paytype));
			return;
		}
		showLoadingDialog();
		pay_commit.setClickable(false);
		RequestParams param = new RequestParams();
		param.addBodyParameter("token", PreferenceUtil.getString(getApplicationContext(), BaseConstant.PREF_TOKE_STRING));
		param.addBodyParameter("pay_type", pay_type);
		param.addBodyParameter("id", detail.getID());
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.POST, API.need_pay, param, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.d("onSuccess==", responseInfo+"");
				pay_commit.setClickable(true);
				Intent in ;
				try {
					JSONObject object = new JSONObject(responseInfo.result);
					if (object.getBoolean("success")) {
						String result = object.getString("result");
						if (!"".equals(CommonUtils.isNull(result))) {
							in = new Intent();
							String packageName = getPackageName();
							ComponentName componentName = new ComponentName(packageName, packageName + ".wxapi.WXPayEntryActivity");
							in.setComponent(componentName);
							in.putExtra(PaymentActivity.EXTRA_CHARGE, result.toString());
							startActivityForResult(in, REQUEST_CODE_PAYMENT);
						}
					}else {
						if (1 == object.getInt("resCode")) {
							in = new Intent(TimeHallDetailActivity.this, LoginActivity.class);
							startActivity(in, true);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Log.d("onFailure==", msg+"");
				NewToast.makeText(getApplicationContext(), "fail"+msg);
				pay_commit.setClickable(true);
			}
		});
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		pay_commit.setClickable(true);
		dismissLoadingDialog();
		//支付页面返回处理
		if (requestCode == REQUEST_CODE_PAYMENT) {
			if (resultCode == Activity.RESULT_OK) {
				String result = data.getExtras().getString("pay_result");
				/* 处理返回值
				 * "success" - payment succeed
				 * "fail"    - payment failed
				 * "cancel"  - user canceld
				 * "invalid" - payment plugin not installed
				 */
				String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
				String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
				NewToast.makeText(getApplicationContext(), result + errorMsg + extraMsg);
				back();
			} else if (resultCode == Activity.RESULT_CANCELED) {
				NewToast.makeText(getApplicationContext(), "User canceled");
			}
		}
		
	}

	private void getData() {

		if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		showDialog(null);
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("ID", ID);
		params.addQueryStringParameter("token", PreferenceUtil.getString(this, BaseConstant.PREF_TOKE_STRING));

		HttpUtils httpUtils = new HttpUtils();

		httpUtils.send(HttpMethod.GET, API.task_detail,params,new RequestCallBack<String>() {

			@Override 
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.d("onSuccess==", responseInfo.result+"");

				dismissLoadingDialog();
				if (responseInfo.result.length() != 0) {
					try {
						JSONObject jsonObject = new JSONObject(responseInfo.result);
						Gson gson = new Gson();
						detail = gson.fromJson(jsonObject.getString("result"),TimeHallDetail.class);
						setData();
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				dismissLoadingDialog();
				Log.d("onFailure==", msg+"");
				NewToast.makeText(getApplicationContext(), R.string.get_country_failure);
			}
		});

	}

	private void taskAccept() {


		if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		showDialog(null);
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("ID", ID);
		params.addQueryStringParameter("NAME", name_et.getText().toString().trim());
		params.addQueryStringParameter("PHONE", phone_et.getText().toString().trim());
		params.addQueryStringParameter("REMARK", youshi_et.getText().toString().trim());
		params.addQueryStringParameter("token", PreferenceUtil.getString(this, BaseConstant.PREF_TOKE_STRING));

		HttpUtils httpUtils = new HttpUtils();

		httpUtils.send(HttpMethod.GET, API.task_accept,params,new RequestCallBack<String>() {

			@Override 
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.d("onSuccess==", responseInfo.result+"");

				dismissLoadingDialog();
				if (responseInfo.result.length() != 0) {
					try {
						JSONObject json = new JSONObject(responseInfo.result);
						boolean isSuccess = json.getBoolean("success");
						if (isSuccess == true) {
							finish();
							NewToast.makeText(TimeHallDetailActivity.this, "揭榜成功");
						}else {
							NewToast.makeText(TimeHallDetailActivity.this, "揭榜失败");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				dismissLoadingDialog();
				Log.d("onFailure==", msg+"");
				NewToast.makeText(getApplicationContext(), R.string.re_loading_failed);
			}
		});


	}
}
